<?php
/**
 * Created by PhpStorm.
 * User: Abel
 * Date: 2016/8/12
 * Time: 11:19
 */

namespace App\Repositories\Remotes;

use GuzzleHttp\Client;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;

class Api
{
    protected $addr;
    protected $client;
    protected $option = [
        'get'  => 'query',
        'post' => 'json',
    ];

    public function __construct($addr)
    {
        $this->client = new Client;
        $this->addr   = $addr;
    }

    public function request($method, array $params = [], $sync = true)
    {
        $options = empty($params)
            ? []
            : [$this->option[ $method ] => $params];

        $method = $sync
            ? $method
            : $method . 'Async';

        $res = $this
            ->client
            ->$method($this->addr, $options);

        return $sync
            ? $this->collect($res)
            : $res->then(function (ResponseInterface $res) {
                return $this->collect($res);
            });
    }

    public function get(array $params = [], $sync = true)
    {
        return $this->request('get', $params, $sync);
    }

    public function post(array $params = [], $sync = true)
    {
        return $this->request('post', $params, $sync);
    }

    /**
     * @param array $params
     * @return PromiseInterface
     */
    public function getAsync(array $params = [])
    {
        return $this->get($params, false);
    }

    /**
     * @param array $params
     * @return PromiseInterface
     */
    public function postAsync(array $params = [])
    {
        return $this->post($params, false);
    }

    protected function collect($res)
    {
        return collect(json_decode($res->getBody()));
    }
}